package org.misty.blog.controller;

import org.misty.blog.po.User;
import org.misty.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {
    private final UserService userService;

    @Autowired
    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public String loginPage(HttpSession session) {
        User user = (User) session.getAttribute("user");
        return user != null ? "admin/index" : "admin/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes) {
        session.removeAttribute("user");
        User user = userService.checkUser(username, password);
        if (user != null) { // 登录成功
            user.setPassword(null);
            session.setAttribute("user", user);
            // 检查是否需要跳转到登录前请求页面
            String prevRequestUri = (String) session.getAttribute("requestUri");
            session.removeAttribute("requestUri");
            if (prevRequestUri != null && !"".equals(prevRequestUri)) {
                return "redirect:" + prevRequestUri;
            }
        } else { // 登录失败
            // 这里不能用Model传递参数
            attributes.addFlashAttribute("message", "用户名/密码错误");
        }
        return "redirect:/admin";
    }

    @RequestMapping("/logout")
    public RedirectView logout(HttpSession session) {
        session.removeAttribute("user");
        return new RedirectView("/");
    }
}
